package com.czy.owner.ui.workorder;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.czy.owner.R;
import com.czy.owner.alipay.PayResult;
import com.czy.owner.api.OrderDetalisApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.SelectOrderDetailsModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.setting.ForgetPaidPasswordActivity;
import com.czy.owner.ui.store.OnLineOrderActivity2;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.widget.MoneyEditText;
import com.czy.owner.wxapi.WXPayEntryActivity;
import com.input.password.ui.InputPwdView;
import com.input.password.ui.MyInputPwdUtil;
import com.input.password.ui.PaidErrorDialog;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wangyang on 2016/6/17.
 * 支付预约金
 */
public class PaidSubscriptionActivity extends BaseActivity {
    @BindView(R.id.tv_paid_dingjin)
    TextView tvPaidDingjin;//定金金额
    @BindView(R.id.tv_use_yue_error)
    TextView tvUseYueError;//提示余额不足

    @BindView(R.id.tv_coupon)
    TextView tvCoupon;//优惠券
    @BindView(R.id.tv_use_yue)
    TextView tvUseYue;//使用余额
    @BindView(R.id.cb_yue)
    CheckBox cbYue;//使用余额CheckBox
    @BindView(R.id.cb_zhifubao)
    CheckBox cbZhiFuBao;//支付宝CheckBox
    @BindView(R.id.cb_weixin)
    CheckBox cbWeiXin;//微信CheckBox
    @BindView(R.id.tv_sdk_paid_tip)
    TextView tvSdkPaidTip;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;

    @BindView(R.id.et_service_despost_price)
    MoneyEditText etServiceDespostPrice;
    //挂账
    @BindView(R.id.relat_bill)
    RelativeLayout relatBill;
    //余额支付
    @BindView(R.id.relat_balance)
    RelativeLayout relatBalance;


    //三方支付
    @BindView(R.id.linear_three_payment)
    LinearLayout linearThreePayment;

    private String orderNumber, userOrderId;

    private static final int SDK_PAY_FLAG = 1;//支付
    private String seletPaidType = "aliPay";
    private double realityPaid; //实际支付
    //    private String useStoreBalance = "false";
    private boolean isUseStoreBalance = false;
    private double storeBalance;
    private double actualDepositAmount;
    //1预约跳转过来，2工单跳转过来
    private String type;
    private int storeId = 0;
    private MyInputPwdUtil myInputPwdUtil;
    private boolean isAllBillAmount;//是否全部挂账支付
    private double billAmount; //挂账金额

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        updataUserInfo();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PhoneUtils.ShowToastMessage(PaidSubscriptionActivity.this, "支付失败");
                    }
                    break;
                }


            }
        }

    };

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_paid_subscription;
    }

    @Override
    protected void initInjector() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setTitle("");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
//            DialogUtils.showDateSuccessDialog(this, type, "你的工单尚未完成支付\n是否放弃支付？", "放弃支付", "继续支付");
            if ("1".equals(type))
                startActivity(new Intent(PaidSubscriptionActivity.this, SubscribeOrdelActivity2.class).putExtra("currentId", 1));
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ("1".equals(type))
                startActivity(new Intent(PaidSubscriptionActivity.this, SubscribeOrdelActivity2.class).putExtra("currentId", 1));
            finish();
//            DialogUtils.showDateSuccessDialog(this, type, "你的工单尚未完成支付\n是否放弃支付？", "放弃支付", "继续支付");
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void initViews() {
        toolbarTitle.setText("支付");
//        getToolbarTitle().setText(R.string.paid_yuyue_money);
        RxBus.getDefault().register(this);
        storeId = getIntent().getIntExtra("storeId", 0);
        orderNumber = getIntent().getStringExtra("orderNumber");
        userOrderId = getIntent().getStringExtra("userOrderId");
        type = getIntent().getStringExtra("type");
        etServiceDespostPrice.setOnEtitClickLinear(new MoneyEditText.OnEtitClickLinear() {
            @Override
            public void editClick(String text) {
                billAmount = Double.parseDouble(text);

                if (Double.parseDouble(text) >= actualDepositAmount) {
                    isAllBillAmount = true;
                    relatBalance.setVisibility(View.GONE);
                    linearThreePayment.setVisibility(View.GONE);
                    tvSdkPaidTip.setVisibility(View.GONE);
                } else {
                    isAllBillAmount = false;
                    relatBalance.setVisibility(View.VISIBLE);
                    linearThreePayment.setVisibility(View.VISIBLE);
                    realityPaid = storeBalance + billAmount - actualDepositAmount;
                    if (realityPaid >= 0) {
                        isUseStoreBalance = true;
                        tvUseYueError.setVisibility(View.GONE);
                    } else {
                        isUseStoreBalance = false;
                        tvUseYueError.setVisibility(View.VISIBLE);
                    }
                    setPaymentText();
                }
            }
        });
        userPayInfoData();
        myInputPwdUtil = new MyInputPwdUtil(this);
        myInputPwdUtil.getMyInputDialogBuilder().setAnimStyle(R.style.ActionSheetDialogAnimation);
        myInputPwdUtil.setListener(new InputPwdView.InputPwdListener() {
            @Override
            public void hide() {
                myInputPwdUtil.hide();
            }

            @Override
            public void forgetPwd() {
                startActivity(new Intent(PaidSubscriptionActivity.this, ForgetPaidPasswordActivity.class));
            }

            @Override
            public void finishPwd(String pwd) {
                bannceVerifyPayPassword(pwd);
            }
        });
    }

    public void setPaymentText() {
        if (cbYue.isChecked()) {
            if (isUseStoreBalance) {
                cbZhiFuBao.setChecked(false);
                cbWeiXin.setChecked(false);
            }
            cbYuEOnClick(cbYue);
        }

    }

    @Override
    protected void updateViews() {

    }


    private void bannceVerifyPayPassword(String payPassword) {
        String url = Constants.APP_API_BASE + Constants.OWN_VERIFYPAYPASSWORD;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(PaidSubscriptionActivity.this).getSession());
        params.addBodyParameter("payPassword", payPassword);
        params.addBodyParameter("userId", UserHelper.getInstance().getUserInfoModel(PaidSubscriptionActivity.this).getUserId() + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                int count = JsonUtil.getJsonValuesInt(result, "data");
                if (flag) {
                    myInputPwdUtil.hide();
                    payDepositAmount();
                } else {
                    switch (count) {
                        case 1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(PaidSubscriptionActivity.this, myInputPwdUtil);
                            break;
                        case 2:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(PaidSubscriptionActivity.this, myInputPwdUtil);
                            break;
                        case 3:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(PaidSubscriptionActivity.this, exp);
                            break;
                        case -1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(PaidSubscriptionActivity.this, exp);
                            break;
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void userPayInfoData() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_PREDEPOSITAMOUNT;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        params.addBodyParameter("orderNumber", orderNumber);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(PaidSubscriptionActivity.this, result);
                MyLog.e("hep", result);
                try {
                    if (data != null) {
                        storeBalance = JsonUtil.getJsonValuesDouble(data, "storeBalance");
                        //String cards = JsonUtil.getJsonValuesString(data, "cards");
                        actualDepositAmount = JsonUtil.getJsonValuesDouble(data, "actualDepositAmount");

                        Double companyId = JsonUtil.getJsonValuesDouble(data, "companyId");
                        Double companyCarId = JsonUtil.getJsonValuesDouble(data, "companyCarId");
                        if (companyCarId > 0 && companyId > 0) {
                            relatBill.setVisibility(View.VISIBLE);
                        }
                        // String couponsList = JsonUtil.getJsonValuesString(data, "couponsList");
                        tvPaidDingjin.setText("¥ " + String.format("%.2f", actualDepositAmount));
                        tvUseYue.setText("¥ " + String.format("%.2f", storeBalance));
                        etServiceDespostPrice.setMaxMoney(actualDepositAmount);
                        etServiceDespostPrice.setShowMessage("挂账金额不能大于订金");
                        if (storeBalance < actualDepositAmount)
                            tvUseYueError.setVisibility(View.VISIBLE);
                        if (storeBalance == 0) {
                            cbYue.setClickable(false);
                        } else {
                            cbYue.setClickable(true);
                        }

                        realityPaid = storeBalance - actualDepositAmount;
                        if (realityPaid >= 0) {
                            isUseStoreBalance = true;
                        } else {
                            isUseStoreBalance = false;
                        }
                    }
                } catch (Exception e) {

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


    //余额支付
    @OnClick(R.id.cb_yue)
    public void cbYuEOnClick(View view) {
        if (!cbWeiXin.isChecked() && !cbZhiFuBao.isChecked() && !cbYue.isChecked()) {
            cbYue.setChecked(true);
            return;
        }
        if (cbYue.isChecked()) {
            if (isUseStoreBalance) {  //当门店余额大于等于实际支付余额时
                cbZhiFuBao.setChecked(false);
                cbWeiXin.setChecked(false);
                cbYue.setChecked(true);
                tvSdkPaidTip.setVisibility(View.GONE);
                tvUseYueError.setVisibility(View.GONE);
            } else {
                tvSdkPaidTip.setVisibility(View.VISIBLE);
                tvUseYueError.setVisibility(View.VISIBLE);
                tvSdkPaidTip.setText("余额可支付¥" + storeBalance + ",还需第三方支付¥" + String.format("%.2f", Math.abs(realityPaid)));
            }

//            useStoreBalance = "true";
        } else {
            tvSdkPaidTip.setVisibility(View.GONE);
//            useStoreBalance = "false";
        }
    }

    //支付宝支付
    @OnClick(R.id.cb_zhifubao)
    public void cbZhiFuBaoOnClick(View view) {
        if (!cbWeiXin.isChecked() && !cbZhiFuBao.isChecked() && !cbYue.isChecked()) {
            cbZhiFuBao.setChecked(true);
            return;
        }
        if (tvSdkPaidTip.getVisibility() == View.VISIBLE && !cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(true);
            return;
        }
        if (cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(false);
            seletPaidType = "aliPay";
            if (realityPaid >= 0 && cbYue.isChecked() == true) {
                cbYue.setChecked(false);
            }
        } else {
            seletPaidType = "11";
        }


    }

    //微信支付
    @OnClick(R.id.cb_weixin)
    public void cbWeiXinOnClick(View view) {
        if (!cbWeiXin.isChecked() && !cbZhiFuBao.isChecked() && !cbYue.isChecked()) {
            cbWeiXin.setChecked(true);
            return;
        }
        if (tvSdkPaidTip.getVisibility() == View.VISIBLE && !cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(true);
            return;
        }
        if (cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(false);
            seletPaidType = "wxPay";
            if (realityPaid >= 0 && cbYue.isChecked() == true) {
                cbYue.setChecked(false);
            }
        } else {
            seletPaidType = "22";
        }


    }

    //确认支付
    @OnClick(R.id.btn_sure_paid)
    public void btnSureOnClick(View view) {
        if (isAllBillAmount) {
            payDepositAmount();
        } else {

            if (cbYue.isChecked()) {
                if (!isUseStoreBalance && !cbZhiFuBao.isChecked() && !cbWeiXin.isChecked()) {
                    PhoneUtils.ShowToastMessage(this, "您还需选择一种三方支付");
                    return;
                }
                myInputPwdUtil.show();
            } else {
                payDepositAmount();
            }
        }


    }

    private void payDepositAmount() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_PAYDEPOSITAMOUNT;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        params.addBodyParameter("orderNumber", orderNumber);
//        if (seletPaidType.equals("aliPay") || seletPaidType.equals("wxPay")) {
//            params.addBodyParameter("payType", seletPaidType);
//        }

        if (cbZhiFuBao.isChecked() && !isAllBillAmount) {
            params.addBodyParameter("payType", "aliPay");

        } else if (cbWeiXin.isChecked() && !isAllBillAmount) {
            params.addBodyParameter("payType", "wxPay");
        }
        params.addBodyParameter("useStoreBalance", isAllBillAmount ? String.valueOf(false) : cbYue.isChecked() + "");

        if (billAmount > 0) {
            params.addBodyParameter("hangAmount", billAmount + "");
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("hep", result);
                String data = PhoneUtils.checkResponseFlag(PaidSubscriptionActivity.this, result);
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");

                if (!flag) {
                    return;
                }
                if (isAllBillAmount) {
                    updataUserInfo();
                } else if (cbYue.isChecked() && !cbWeiXin.isChecked() && !cbZhiFuBao.isChecked()) {
                    updataUserInfo();
                } else {
                    if (cbZhiFuBao.isChecked()) {
                        aliPayPaid(data);
                    } else if (cbWeiXin.isChecked()) {
                        if (isWXAppInstalledAndSupported()) {
                            WXPayEntryActivity.wxPayPaidStart(PaidSubscriptionActivity.this, data, "支付定金成功");
                        } else {
                            PhoneUtils.ShowToastMessage(PaidSubscriptionActivity.this, getString(R.string.isInstallwx));
                        }
                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    //判断是否安装微信客户端
    public boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(WXPayEntryActivity.APP_ID);
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled() && msgApi.isWXAppSupportAPI();
        return sIsWXAppInstalledAndSupported;
    }

    private void aliPayPaid(final String data) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PaidSubscriptionActivity.this);
                // 调用支付接口，获取支付结果
                Map<String, String> result = alipay.payV2(data, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    private void updataUserInfo() {
        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
        Intent intent = new Intent();
        intent.setAction(SubscribeOrdelActivity.orderAction);
        if (SubscribeOrdelActivity.currentId() == 0) {
            intent.putExtra("currentId", 2);
        } else if (SubscribeOrdelActivity.currentId() == 1) {
            intent.putExtra("currentId", 2);
        }
        sendBroadcast(intent);
//        RxBus.getDefault().post(Constants.PAID_SUCCESS_ENDOF_PAYMENT, new CommonEvent("详情定金支付成功"));
        RxBus.getDefault().post(new CommonEvent("详情定金支付成功"));
        getOrderSuccess();
    }

    //获取详情
    private void getOrderSuccess() {
        OrderDetalisApi ownerCarApi = new OrderDetalisApi(new HttpOnNextListener<SelectOrderDetailsModel>() {
            @Override
            public void onNext(SelectOrderDetailsModel o) {
                showDateSuccessDialog(o);
            }


            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                Toast.makeText(PaidSubscriptionActivity.this, "支付成功获取订单信息异常", Toast.LENGTH_SHORT).show();
            }
        }, this);

        ownerCarApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        ownerCarApi.setStoreId(storeId + "");

        ownerCarApi.setUserOrderId(userOrderId);
        HttpManager.getInstance().doHttpDeal(ownerCarApi);
    }

    //成功提示
    private void showDateSuccessDialog(SelectOrderDetailsModel selectOrderDetailsModel) {
        final Dialog mDateSuccessDialog;
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        mDateSuccessDialog = new Dialog(this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_order_submit_success, null);
        TextView tv_order_num = (TextView) dialogView.findViewById(R.id.tv_order_num);
        TextView tv_car_num = (TextView) dialogView.findViewById(R.id.tv_car_num);
        TextView tv_time = (TextView) dialogView.findViewById(R.id.tv_time);
        TextView tv_details = (TextView) dialogView.findViewById(R.id.tv_details);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);
        mDateSuccessDialog.setContentView(dialogView);

        tv_order_num.setText(StringUtils.getNum(selectOrderDetailsModel.getStoreBookingNumber()));
        tv_car_num.setText(selectOrderDetailsModel.getLicenseNumber());
        tv_details.setText(selectOrderDetailsModel.getItemName());
        tv_time.setText(selectOrderDetailsModel.getConvertServiceTime());
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(type)) {
                    startActivity(new Intent(PaidSubscriptionActivity.this, SubscribeOrdelActivity2.class).putExtra("currentId", 2));
                }
                mDateSuccessDialog.dismiss();
                finish();

            }
        });

        Window dialogWindow = mDateSuccessDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mDateSuccessDialog.setCancelable(false);
        mDateSuccessDialog.show();
    }


    @Subscribe(code = Constants.ORDER_PAID_SUCCESS, threadMode = ThreadMode.MAIN)
    public void eventPaidSuccess(CommonEvent paidSuccessEvent) {
        updataUserInfo();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
